<?php

/**
 * 船票订单控制器
 * 处理船票订单的创建、支付、查询等相关业务
 */

declare(strict_types=1);

namespace app\index\controller\order;

use app\common\model\order\ShipOrder as ShipOrderModel;
use app\common\service\Util;
use app\common\service\third_party_api\PayApiService;
use think\facade\Request;
use think\facade\Db;
use think\Exception;
use app\common\ConstVar;
use think\facade\Log;
use app\index\logic\order\ShipOrderLogic;

/**
 * 船票订单控制器类
 * 负责处理船票订单的各项操作
 */
class ShipOrder extends Order
{

    /**
     * 船票订单详情
     * @param int $id 订单ID
     * @return void
     */
    public function info(int $id)
    {
        // 验证订单归属
        if (!$this->checkOrderOwnership($id, ShipOrderModel::class)) {
            return Util::ajaxReturn(0, '无权查看该订单', []);
        }

        $logic = new \app\index\logic\order\ShipOrderLogic();
        $data = $logic->getOrderDetail($id);

        return Util::ajaxReturn(1, 'OK', $data);
    }

    /**
     * 删除船票订单
     * @param int $id 订单ID
     * @return void
     */
    public function delete(int $id)
    {
        // 验证订单归属
        if (!$this->checkOrderOwnership($id, ShipOrderModel::class)) {
            return Util::ajaxReturn(0, '无权删除该订单', []);
        }

        $shipOrderModel = new ShipOrderModel();
        $shipOrderModel->where('id', $id)->delete();

        return Util::ajaxReturn(1, 'OK', []);
    }

    /**
     * 获取指定日期的船票服务费
     * @param Request $request 请求对象
     * @return void
     */
    public function charge(Request $request)
    {
        $date = $request::get('date');
        $shipOrderModel = new ShipOrderModel();

        return Util::ajaxReturn(1, 'OK', $shipOrderModel->getDateCharge($date, $this->user_info));
    }

    /**
     * 船票订单支付
     * @param int $id 订单ID
     * @return void
     */
    public function pay()
    {
        $id = intval(input('id', '0'));
        $type = intval(input('type', 1));

        $payApiService = new PayApiService();
        if ($type === 1) {
            if (!$this->user_info['openid']) {
                return Util::ajaxReturn(0, 'weixin_unbind');
            }

            $config = $payApiService->wxPay($type, $id, $this->user_info['openid']);

            return Util::ajaxReturn(1, '请支付', ['pay_data' => $config]);
        } elseif ($type === 2) {
            $config = $payApiService->aliPay($type, $id);

            return Util::ajaxReturn(1, '请支付', ['pay_data' => $config]);
        }
    }

    /**
     * 船票订单下单
     * @return void
     * @throws Exception 当参数验证失败或下单过程出错时抛出异常
     */
    public function bookingShip()
    {
        // 获取并格式化订单参数
        $data['booking_tel'] = (string)trim(input('param.bookingTel'));
        $data['total'] = floatval(input('param.total'));
        $data['contact_name'] = (string)trim(input('param.contactName'));
        $data['contact_list'] = (array)input('param.contactList');
        $data['choose_seat'] = (array)input('param.chooseSeat');
        $data['choose_flight'] = (array)input('param.chooseFlight');
        $data['island_tickets'] = (array)input('param.islandTickets', []);
        $data['is_buy_ticket'] = (string)input('param.isBuyTicket');
        $data['charge'] = (string)input('param.charge', 0);
        $data['is_date'] = intval(input('param.isdate', 0));
        $data['need_sms'] = input('param.sms', 0);
        $data['take_children'] = (array)input('param.takeChildren');
        $data['children_charge'] = floatval(input('param.childrenCharge'));
        $data['user_id'] = $this->user_id;
        $data['user_info'] = $this->user_info;

        if ($this->user_info['is_black'] === 2) {
            return Util::ajaxReturn(0, '您已被限制购买，请联系客服', []);
        }

        if (!$data['agree']) {
            return Util::ajaxReturn(0, '购买船票必须同意须知、协议', []);
        }

        if (empty($data['contact_list'])) {
            return Util::ajaxReturn(0, '乘客不能为空', []);
        }

        if (!$data['booking_tel']) {
            return Util::ajaxReturn(0, '联系电话不能为空', []);
        }

        if ($data['is_date'] === 1) {
            if ($data['booking_tel'] !== $this->user_info['tel']) {
                return Util::ajaxReturn(0, '旺季不可更改手机号码', []);
            }
        }

        if (!$data['contact_name']) {
            return Util::ajaxReturn(0, '请填写联系人', []);
        }
        $data['island_goods'] = null;
        if ($data['is_buy_ticket']) {
            if (empty($data['island_tickets'])) {
                return Util::ajaxReturn(0, '上岛票不能为空', []);
            }
            $goodsId = ConstVar::$island_goods_id;
            if (!$data['island_goods'] = db('goods')->find($goodsId)) {
                return Util::ajaxReturn(0, '上岛票商品不存在', []);
            }
        }
        $shipline = Db::name('ship_line')->where(['line_id' => $data['choose_flight']['line_id'],])->find();

        if (!$shipline) {
            return Util::ajaxReturn(0, '航线不存在', []);
        }
        if (count($data['contact_list']) > 10) {
            return Util::ajaxReturn(0, '最多添加10个乘客', []);
        }
        $shipOrderModel = new ShipOrderModel();
        $shipOrderId = $shipOrderModel->bookingShip($data);

        return Util::ajaxReturn(1, '请付款', ['pay_data' => $shipOrderId]);
    }

    /**
     * 记录用户无座位协童登记数据
     * @param int $ship_order_id 订单ID
     * @param array $take_children 协童数据
     * @return bool
     */
    public function recordChildrenData(int $ship_order_id, array $take_children): bool
    {
        $ship_order_id = intval($ship_order_id);
        if ($ship_order_id <= 0) {
            return false;
        }
        if (!$take_children) {
            return false;
        }
        $shipOrderModel = new ShipOrderModel();
        return $shipOrderModel->recordChildrenData($ship_order_id, $take_children, $this->user_id);
    }

    /**
     * 订单退款
     * @return void
     */
    public function refund()
    {
        $id = intval(input('id', '0'));
        $reason = trim(input('reason', ''));
        $refundList = input('refund_list/a', []);

        if ($id <= 0) {
            return Util::ajaxReturn(0, '订单ID不能为空', []);
        }

        $logic = new \app\index\logic\order\ShipOrderLogic();
        $result = $logic->applyRefundShipOrder($id, $this->user_id, $reason, $refundList);

        if ($result['success']) {
            return Util::ajaxReturn(1, $result['message'], []);
        } else {
            return Util::ajaxReturn(0, $result['message'], []);
        }
    }

    /**
     * 根据部分退款表的refund_list字段和船票订单表的contact_list字段比较，获取船票订单中还未退款的游客列表
     * @return void
     */
    public function getUnrefundContactList()
    {
        $orderId = intval(input('order_id', '0'));
        if ($orderId <= 0) {
            return Util::ajaxReturn(0, '订单ID不能为空', []);
        }

        $logic = new \app\index\logic\order\ShipOrderLogic();
        $unrefundContactList = $logic->getUnrefundContactList($orderId, $this->user_id);

        return Util::ajaxReturn(1, '获取成功', $unrefundContactList);
    }

    /**
     * 船票订单改签
     * @param int $id 订单ID
     * @return void
     */
    public function change(int $id): bool
    {
        $id = intval($id);
        if ($id <= 0) {
            return false;
        }

        // 获取请求参数
        $param = Request::param();

        try {
            // 调用逻辑层处理改签业务
            $shipOrderLogic = new ShipOrderLogic();
            $result = $shipOrderLogic->changeShipOrder($id, $this->user_id, $param);

            return $result['success'] ?? false;
        } catch (\Exception $e) {
            Log::error('船票改签控制器异常，订单ID: ' . $id . '，异常信息: ' . $e->getMessage());
            return false;
        }
    }
}
